import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:grocery_app_demo/api/entity/login_res_entity.dart';
import 'package:grocery_app_demo/api/scm_api.dart';
import 'package:grocery_app_demo/core/utils/global.dart';
import 'package:grocery_app_demo/routes/app_routes.dart';

class LoginController extends GetxController {
  RxBool showPassword = false.obs;
  TextEditingController usernameCtrl = TextEditingController();
  TextEditingController passwordCtrl = TextEditingController();

  RxBool canLogin = false.obs;

  String get username => usernameCtrl.value.text;

  String get password => passwordCtrl.value.text;

  IconData get passwordSuffixIcon =>
      showPassword.isTrue ? Icons.visibility : Icons.visibility_off;


  @override
  void onInit() {
    usernameCtrl.text = 'admin';
    passwordCtrl.text = '123456';
    checkInput(null);
    super.onInit();
  }

  void login() {
    ScmApi().post<LoginResEntity>(ScmApi.login,
        data: {'username': username, 'password': password}).then((value) {
      Global.token = value.accessToken;
      Global.setString(SpKey.refreshToken, value.refreshToken);
      Global.setInt(SpKey.tokenExpiresTime, value.expiresTime);
      Get.offAllNamed(AppRoutes.purchase);
    });
  }

  void checkInput(String? value) {
    canLogin.value = username.trim().isNotEmpty && password.trim().isNotEmpty;
  }
}
